package com.demo.demo_scan;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.imageio.ImageIO;

import com.google.zxing.BinaryBitmap;
import com.google.zxing.DecodeHintType;
import com.google.zxing.LuminanceSource;
import com.google.zxing.MultiFormatReader;
import com.google.zxing.NotFoundException;
import com.google.zxing.Result;
import com.google.zxing.ResultPoint;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.common.HybridBinarizer;

public class XzingBarApp {

	public static void main(String[] args) {
		try {
			String dir = System.getProperty("user.dir").replace("/", "\\");
			String imgUrl = dir.concat("\\img\\BRz.jpg");
			File imageFile = new File(imgUrl);
			BufferedImage bufferedImage = ImageIO.read(imageFile);

			Result result = decodeBarCode(bufferedImage);

			if (result != null) {

				System.out.println("Decoded text: " + result.getText());

//				// 获取位置信息
//
//				ResultPoint[] points = result.getResultPoints();
//
//				int[] position = new int[8]; // 每个点两个坐标
//
//				for (int i = 0; i < points.length; i++) {
//
//					ResultPoint point = points[i];
//
//					position[i * 2] = (int) point.getX();
//
//					position[i * 2 + 1] = (int) point.getY();
//
//				}
//				
//				int x = position[0]-100;
//				int width = position[2]- x+50;
//				int y = position[1]-50;
//				int height = width/2+50;
//				
//				BufferedImage croppedImage = bufferedImage.getSubimage(x, y, width, height);
//
//				// 保存裁剪后的图片
//				String outimgUrl = dir.concat("\\img\\4t1.jpg");
//				ImageIO.write(croppedImage, "jpg", new File(outimgUrl));

			}
		} catch (IOException | NotFoundException e) {
			e.printStackTrace();
		}
	}

	private static Result decodeBarCode(BufferedImage image) throws NotFoundException {
		LuminanceSource source = new BufferedImageLuminanceSource(image);
		BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
		Map<DecodeHintType, Object> hints = new HashMap<DecodeHintType, Object>();
		hints.put(DecodeHintType.CHARACTER_SET, "UTF-8");
		hints.put(DecodeHintType.TRY_HARDER, Boolean.TRUE);
		return new MultiFormatReader().decode(bitmap, hints);
	}
}